package com.zzs.judge.dao.redis;

import com.zzs.common.core.constant.RedisKeyConsts;
import com.zzs.common.core.entity.mysql.ProblemCodeDO;
import com.zzs.common.core.entity.redis.ProblemCodeCache;
import com.zzs.common.core.enums.ResponseCode;
import com.zzs.common.redis.service.RedisService;
import com.zzs.common.security.exception.ServiceException;
import com.zzs.judge.dao.mysql.ProblemCodeMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * @author zzs
 * @date 2025/03/27
 */
@Repository
public class ProblemCodeCacheManager {
    @Autowired
    private RedisService redisService;

    @Autowired
    private ProblemCodeMapper problemCodeMapper;

    public ProblemCodeCache getProblemCodeCache(long problemId, int language) {
        String key = RedisKeyConsts.getProblemCodeKey(problemId, language);
        ProblemCodeCache problemCodeCache = redisService.getValue(key, ProblemCodeCache.class);
        if (problemCodeCache == null) {
//            redis不存在题目代码缓存, 从mysql查
            ProblemCodeDO problemCode = problemCodeMapper.getProblemCode(problemId, language);
            if (problemCode == null) {
                throw new ServiceException(ResponseCode.NOT_FOUND);
            }
            problemCodeCache = new ProblemCodeCache();
            BeanUtils.copyProperties(problemCode, problemCodeCache);
//            刷新redis
            redisService.saveValue(key, problemCodeCache);
        }
        return problemCodeCache;
    }
}
